﻿using Microsoft.Extensions.Caching.StackExchangeRedis;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using ShenNius.BasePackage.Caches;
using ShenNius.BasePackage.FileManage;
using ShenNius.BasePackage.FileManager;
using ShenNius.ModuleCore;
using ShenNius.ModuleCore.Context;
using ShenNius.ModulePackage.Caches;
using ShenNius.ModulePackage.Db;
using System;

/*************************************
* 类名：ShenNiusBasePackageModule
* 作者：realyrare
* 邮箱：mhg215@yeah.net
* 时间：2021/9/9 19:09:16
*┌───────────────────────────────────┐　    
*│　   版权所有：神牛软件　　　　	     │
*└───────────────────────────────────┘
**************************************/

namespace ShenNius.BasePackage
{
    public class ShenNiusBasePackageModule:AppModule
    {
        public override void OnConfigureServices(ServiceConfigurationContext context)
        {     
            RecycleSetting.allTableName = context.Configuration["DbTable:Value"];
            //事务使用AOP 所以注入下。
            context.Services.AddScoped<DbContext>();          
            //注入泛型BaseServer
            context.Services.AddScoped(typeof(IBaseServer<>), typeof(BaseServer<>));

            //redis和cache配置
            var redisConfiguration = context.Configuration.GetSection("Redis");
            context.Services.Configure<RedisOption>(redisConfiguration);
            RedisOption redisOption = redisConfiguration.Get<RedisOption>();
            if (redisOption != null && redisOption.Enable)
            {
                var options = new RedisCacheOptions
                {
                    InstanceName = redisOption.InstanceName,
                    Configuration = redisOption.Connection
                };
                var redis = new RedisCacheHelper(options, redisOption.Database);
                context.Services.AddSingleton(redis);
                context.Services.AddSingleton<ICacheHelper>(redis);
            }
            else
            {
                context.Services.AddMemoryCache();
                context.Services.AddScoped<ICacheHelper, MemoryCacheHelper>();
            }

            //是否启用本地文件上传 选择性注入
            var enableLocalFile = Convert.ToBoolean(context.Configuration["LocalFile:IsEnable"]);
            if (enableLocalFile)
            {
                context.Services.AddScoped<IUploadHelper, LocalFile>();
            }
            else
            {
                //七牛云配置信息读取
                context.Services.Configure<QiNiuOss>(context.Configuration.GetSection("QiNiuOss"));
                context.Services.AddScoped<IUploadHelper, QiniuCloud>();
            }

        }
        public override void OnApplicationInitialization(ApplicationInitializationContext context)
        {       
            NLog.LogManager.LoadConfiguration("nlog.config").GetCurrentClassLogger();
            NLog.LogManager.Configuration.Variables["connectionString"] = context.Configuration["ConnectionStrings:MySql"];
        }
    }
}